﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NcfDB.Model
{
    class Row
    {
        protected Dictionary<string, object> data;
        public Dictionary<string,object>.KeyCollection Columns { get { return data.Keys; } }
        public Dictionary<string, object>.ValueCollection Values { get { return data.Values; } }
        public object this[string Column]
        {
            get
            {
                if (!data.Keys.Contains(Column)) throw new IndexOutOfRangeException("指定的字段名不存在");
                return data[Column];
            }
            set
            {
                data[Column] = value;
            }
        }
        public Row()
        {
            this.data = new Dictionary<string, object>();
        }
        public void setData(Dictionary<string, object> data)
        {
            this.data = data;
        }
        public static Row readFromStream(Table table,ref FileStream fs, ref StreamReader sr)
        {
            int count = table.FieldProperty.Count;
            string key;
            object value;
            //StreamReader sr = new StreamReader(fs);
            Row row = new Row();
            row.data = new Dictionary<string, object>();
            //value = sr.ReadLine();
            //if (value == null || value == "~") return null;
            for (int i = 0; i < count; i++ )
            {
                value = sr.ReadLine();
                if (value == null || value.ToString() == "~") return null;
                key = table.fieldOrder[i];
                row.data.Add(key, value);
            }
            return row;
        }

        public void save(Table table,ref FileStream fs)
        {
            StreamWriter sw = new StreamWriter(fs);
            int count = this.data.Count;
            for (int i = 0; i < count ; i++)
            {
                if (this[table.fieldOrder[i]] == null)
                    sw.WriteLine("");
                else
                    sw.WriteLine(this[table.fieldOrder[i]]);
            }
            sw.Flush();
        }
    }
}
